<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="850px"
    append-to-body
    :close-on-click-modal="false"
    @close="closeModal"
  >
    <el-form ref="form" :model="form" :show-message="false" label-width="110px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位名称" prop="cname" required>
            <el-input v-model="form.cname" placeholder="请输入单位名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属渠道" prop="channelId" required>
            <div v-if="userInfo.userType === 2">{{ form.channelName }}</div>
            <Treeselect
              v-else
              ref="Treeselect"
              v-model="form.channelId"
              :options="channelOptions"
              :show-count="true"
              placeholder="请选择渠道"
              noResultsText="暂无数据"
              @input="handChangeChannel"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属行业" prop="industry">
            <el-select
              v-model="form.industry"
              placeholder="请选择所属行业"
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.industry"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位法人" prop="legalname">
            <el-input v-model="form.legalname" placeholder="请输入单位法人" />
          </el-form-item>
        </el-col>
        <template v-if="userInfo.userType === 1">
          <el-col :span="12">
            <el-form-item label="单位跟进人" prop="businessUserId">
              <SelectBusinessUser
                v-if="open"
                :defaultValue.sync="form.businessUserId"
                :channelId="form.channelId"
                :disabled="!form.channelId"
                @change="businessUserChange"
                placeholder="请先选择渠道,再选择单位跟进人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跟进人部门" prop="businessDeptName">
              {{ form.businessDeptName }}
            </el-form-item>
          </el-col>
        </template>

        <el-col :span="12">
          <el-form-item label="单位等级" prop="levels" required>
            <el-select
              v-model="form.levels"
              placeholder="请选择单位等级"
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.company_level"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位类型" prop="comtype" required>
            <el-select
              v-model="form.comtype"
              placeholder="请选择单位类型"
              style="width: 100%"
            >
              <el-option
                v-for="dict in dict.type.company_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位联系人" prop="contactName" required>
            <el-input
              v-model="form.contactName"
              placeholder="请输入联系人姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="联系人电话" prop="phone">
            <el-input
              v-model="form.phone"
              maxlength="20"
              placeholder="请输入联系人电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="单位地址" prop="province" required>
            <div class="disFlxAC">
              <el-cascader
                v-if="open && !mapOpen"
                style="width: 100%"
                :options="options"
                :props="props"
                v-model="areaList"
                @change="changeAreaList"
                required
              ></el-cascader>
              <div
                @click="mapOpen = true"
                style="width: 60px"
                class="disFlxCC colorZS"
              >
                <i class="iconfont el-icon-location fz-28" />
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细地址" prop="address" required>
            <el-input v-model="form.address" placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="单位简介" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="2"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位主图" prop="cimg1">
            <ImageUpload v-model="form.cimg1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位二维码" prop="wxmpUrl">
            <ImageUpload v-model="form.wxmpUrl" cropper />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="营业执照" prop="businessimg">
            <ImageUpload v-model="form.businessimg" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医疗机构执业许可证" prop="miplImg">
            <ImageUpload v-model="form.miplImg" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="borderT pt-20">
        <el-col :span="12">
          <el-form-item label="管理员姓名" prop="adminname" required>
            <el-input v-model="form.adminname" placeholder="请输入管理员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="honorific" required>
            <el-radio-group v-model="form.honorific">
              <el-radio
                v-for="dict in dict.type.sys_user_sex"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理员手机号" prop="mobile" required>
            <el-input
              v-model="form.mobile"
              maxlength="20"
              placeholder="请输入管理员手机号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理员账号" prop="adminacc" required>
            <el-input
              v-model="form.adminacc"
              :disabled="adminaccDisabled"
              placeholder="请输入管理员账号"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="borderT pt-20">
        <template v-if="userInfo.userType === 1">
          <el-col :span="24">
            <el-form-item label="单位服务商" prop="serviceCompanyIds">
              <el-select
                v-model="serviceCompanyItems"
                multiple
                filterable
                :placeholder="`请选择服务商`"
                clearable
                :disabled="!form.channelId"
                style="width: 100%"
                value-key="id"
              >
                <el-option
                  v-for="item in serviceCompanyOptions"
                  :key="item.id"
                  :label="item.cname"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审证审方机构" prop="apPrescriptionCompanyId">
              <SelectCompany
                v-if="open"
                :defaultValue.sync="form.apPrescriptionCompanyId"
                :companyType="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审证审方人" prop="apPrescriptionExpertId">
              <SelectExpert
                v-if="open"
                :defaultValue.sync="form.apPrescriptionExpertId"
                :comId="form.apPrescriptionCompanyId"
                :prescriptionFlag="1"
                @change="changeExpert"
              />
            </el-form-item>
          </el-col>
        </template>

        <el-col :span="24">
          <el-form-item label="渠道分润比例" prop="channelFee">
            <div class="disFlx">
              <el-input-number
                :precision="0"
                v-model="form.channelFee"
                placeholder="请输入"
                :min="0"
                :max="100"
                :disabled="form.id && form.id === userInfo.comId"
              />
              <span class="pl-2">%</span>
            </div>
            <div class="fz-12 linh-20 pt-5">
              该比例为咨询订单的分润比例，如单笔咨询单100元，若分润比例为20%，
              则渠道收益为20元。此处需和单位协商后再填写。
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="userInfo.userType != 2">
          <el-form-item label="PAD菜单权限" prop="menuId">
            <el-checkbox-group v-model="form.menuId">
              <el-checkbox
                v-for="(item, index) in baseList"
                :key="index"
                :label="item.menuId"
                >{{ item.menuName }}</el-checkbox
              >
            </el-checkbox-group>
            <div class="fz-12 linh-20">
              勾选此菜单后，单位专家能看到平台所有专家资源数据
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="入驻平台申请" prop="apstatus">
            <div
              v-if="
                form.apstatus != 3 && form.apstatus != 4 && form.apstatus != 5
              "
              class="fw-6 color3"
            >
              <dict-tag :options="dict.type.apstatus" :value="form.apstatus" />
            </div>
            <div v-else>
              <el-radio-group v-model="form.apstatus">
                <el-radio label="5">申请入驻平台</el-radio>
                <el-radio label="4">不申请</el-radio>
              </el-radio-group>
              <div class="fz-12 linh-20">
                <span v-if="form.apstatus == 3" style="color: red"
                  >入驻审核被拒绝,可重新申请</span
                >
                入驻成功后，专家可获得平台曝光量和更多用户咨询。
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>

    <mapDialog :visible.sync="mapOpen" @handelAddress="locationSure" />
  </el-dialog>
</template>

<script>
import { treeselect } from "@/api/channel/channel";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listArea } from "@/api/saas/area";
import mapDialog from "@/components/IbsAmap/mapDialog";
import ImageUpload from "@/components/ImageUpload";
import {
  appmenuBaseList,
  addCompany,
  updateCompany,
  getCompany,
} from "@/api/company/company";
import SelectBusinessUser from "@/views/system/user/selectBusinessUser";
import SelectCompany from "@/components/SelectCompany";
import SelectExpert from "@/views/expert/expert/selectExpert.vue";
import { cooperateCompanyLists } from "@/api/facilitator";

export default {
  dicts: [
    "industry",
    "company_level",
    "company_type",
    "sys_user_sex",
    "apstatus",
  ],
  components: {
    Treeselect,
    mapDialog,
    ImageUpload,
    SelectBusinessUser,
    SelectCompany,
    SelectExpert,
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
  data() {
    const that = this;
    return {
      title: "新增单位",
      open: false,
      form: {
        id: undefined,
        companyType: 0, // 机构类型: 0单位 1服务商
        cname: "", // 单位名称
        channelId: null, // 渠道ID
        channelName: undefined, // 渠道名称
        industry: undefined, // 所属行业
        legalname: "", // 单位法人
        businessUserId: undefined, // 单位跟进人
        businessDeptName: "", // 跟进人部门
        levels: undefined, // 单位等级
        comtype: undefined, // 单位类型
        contactName: "", // 单位联系人
        phone: "", // 联系人电话
        province: "", // 省
        city: "", // 市
        distincts: "", // 区
        address: "", // 详细地址
        cimg1: "", // 主图
        wxmpUrl: "", // 单位二维码
        businessimg: "", // 单位营业执照
        miplImg: "", // 医疗机构执业许可证
        remarks: "", // 单位简介

        adminname: "", // 管理员姓名
        honorific: "0", // 性别
        mobile: "", // 管理员手机号
        adminacc: "", // 管理员账号

        serviceCompanyIds: "", // 单位服务商
        apPrescriptionCompanyId: null, // 审证审方机构
        apPrescriptionExpertId: null, // 审证审方人
        channelFee: 0, // 渠道分润比例
        menuId: [], // PAD菜单权限
        apstatus: "4", // 是否入驻4不申请,5申请
      },

      // 渠道树选项
      channelOptions: [],
      mapOpen: false,
      areaList: [],
      // 省市区级联
      options: [],
      props: {
        label: "name",
        value: "id",
        lazy: true,
        lazyLoad(node, resolve) {
          let clevel = node.level + 1;
          console.log(node, clevel, "监听省市区变化");
          listArea({ pid: node.value, level: clevel }).then((res) => {
            if (clevel === 3) {
              res.data.forEach((v) => {
                that.$set(v, "leaf", true);
              });
              if (!res.data) {
                this.form.distincts = "";
              }
            }
            resolve(res.data);
          });
        },
      },
      // 菜单权限
      baseList: [],
      serviceCompanyOptions: [], // 服务商列表
      serviceCompanyItems: [], // 选中的服务商对象列表
      adminaccDisabled: false, // 管理员账号是否禁用
    };
  },
  created() {
    this.getTreeselect();
  },
  methods: {
    openModal(id) {
      this.getAppmenuBaseList();
      this.title = id ? "编辑单位" : "新增单位";
      this.form.id = id || undefined;
      this.form.id ? this.getData() : (this.open = true);
    },
    closeModal() {
      Object.assign(this.$data.form, this.$options.data().form); // 存在自定义校验规则不能重置data
      this.serviceCompanyItems = [];
      this.areaList = [];
      this.adminaccDisabled = false;
      this.open = false;
    },
    // 获取详情
    getData() {
      getCompany(this.form.id).then((response) => {
        this.form = response.data;
        this.getCooperateCompanyLists(this.form.channelId);
        this.form.channelFee ? this.form.channelFee : 0;
        this.form.province ? this.areaList.push(this.form.province) : "";
        this.form.city ? this.areaList.push(this.form.city) : "";
        this.form.distincts ? this.areaList.push(this.form.distincts) : "";
        this.form.apstatus = String(this.form.apstatus);
        if (this.form.serviceCompanyList) {
          this.serviceCompanyItems = this.form.serviceCompanyList;
        }
        this.adminaccDisabled = !!this.form.adminacc; // 管理员账号已存在时不允许修改
        this.open = true; // 影响省市区回显
      });
    },
    async submitForm() {
      const that = this;
      that.form.serviceCompanyIds = that.serviceCompanyItems
        .map((v) => v.id)
        .join(",");
      console.log(JSON.parse(JSON.stringify(that.form)), "提交表单");
      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (that.form.id) {
            await updateCompany(that.form);
          } else {
            await addCompany(that.form);
          }

          that.$message.success(that.form.id ? "修改成功" : "新增成功");
          that.$emit("refresh");
          that.closeModal();
        }
      });
    },
    /** 查询渠道下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.channelOptions = response.data;
      });
    },
    handChangeChannel(e) {
      this.$refs.form.validateField("channelId");
      if (e) {
        this.getCooperateCompanyLists(e);
      } else {
        this.serviceCompanyItems = [];
        this.serviceCompanyOptions = [];
      }
    },
    getCooperateCompanyLists(channelId) {
      cooperateCompanyLists({ channelId, pageSize: 999 }).then((res) => {
        this.serviceCompanyOptions = res.rows.map((v) => {
          return {
            id: v.companyId,
            cname: v.companyName,
          };
        });
      });
    },
    locationSure(e) {
      this.areaList = e.areaList;
      this.changeAreaList(e.areaList);
      this.form.address = e.address;
      console.log(e, "地图选点", this.form);
    },
    // 省市区选择
    changeAreaList(e) {
      e.forEach((item, index) => {
        if (index === 0) {
          this.form.province = item;
          this.form.city = "";
          this.form.distincts = "";
        }
        if (index === 1) {
          this.form.city = item;
          this.form.distincts = "";
        }
        if (index === 2) {
          this.form.distincts = item;
        }
      });
    },
    // 获取菜单列表
    getAppmenuBaseList() {
      appmenuBaseList().then((res) => {
        this.baseList = res.data;
      });
    },
    // 跟进人选择
    businessUserChange(e) {
      if (e && e.dept) {
        this.form.businessDeptName = e.dept.deptName;
      } else {
        this.form.businessDeptName = "";
      }
    },
    // 审证审方人选择
    changeExpert(item) {
      if(item && this.form.apPrescriptionCompanyId !== item.comId){
        this.form.apPrescriptionCompanyId = item.comId;
        setTimeout(() => {
          this.form.apPrescriptionExpertId = item.id;
        }, 100);
      }
    }
  },
};
</script>

<style lang="scss" scoped></style>
